﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using FarseerPhysics.Dynamics;
using FarseerPhysics;
using FarseerPhysics.DebugViews;
using FarseerPhysics.Factories;
using FarseerPhysics.SamplesFramework;

namespace BattleToast
{


    public partial class GamePage : PhoneApplicationPage
    {
        private DebugViewXNA debugView;
        private SpriteBatch spriteBatch;
        private World world;
        ContentManager contentManager;
        private float floorTimer, fanTimer;
        GameTimer timer;
        int space=1;
        float fanSpace = 6.0f;
        MainCharacter Toast;
        Vector2 lastPosition;
        List<GameObject> floors;
        List<AnimatedGameObject> fans;
        Random randomFloor, randomFan;
        AnimatedGameObject fire;

        double height = (App.Current.RootVisual as FrameworkElement).ActualHeight;
        double width = (App.Current.RootVisual as FrameworkElement).ActualWidth;
        

        public GamePage()
        {

            InitializeComponent();


            // Get the content manager from the application
            contentManager = (Application.Current as App).Content;

            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            if (world == null)
            {
                world = new World(new Vector2(0, 20f));
            }
            else
            {
                world.Clear();
            }

            if (debugView == null)
            {
                debugView = new DebugViewXNA(world);
                debugView.RemoveFlags(DebugViewFlags.Controllers);
                debugView.RemoveFlags(DebugViewFlags.Joint); 
                debugView.LoadContent(SharedGraphicsDeviceManager.Current.GraphicsDevice, contentManager);
            }


            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            // TODO: use this.Content to load your game content here
           
            //TOAST
            Vector2 toastPosition = new Vector2(100, 100);
            Vector2 toastSize = new Vector2(133, 77);
            Texture2D toastTexture = contentManager.Load<Texture2D>("images\\Tost");
            Toast = new MainCharacter(world, toastTexture, toastPosition, toastSize, 1, 50, null);
            Toast.Position = toastPosition;
            Toast.Size = toastSize;
            Toast.Body = BodyFactory.CreateRectangle(world, ConvertUnits.ToSimUnits(toastSize.X), ConvertUnits.ToSimUnits(toastSize.Y), 10f);
            Toast.Body.Position = ConvertUnits.ToSimUnits(toastPosition.X, toastPosition.Y);
            Toast.Body.BodyType = BodyType.Dynamic;
            Toast.Body.Restitution = 0.2f;
            Toast.Body.Friction = 0.2f;

            //drawing the floor
            floors = new List<GameObject>();
            floors.Add(DrawFloor(new Vector2(100,200)));
            floors.Add(DrawFloor(new Vector2(420, 250)));
            floors.Add(DrawFloor(new Vector2(800, 270)));

            //drawing the fan
            fans = new List<AnimatedGameObject>();
            fans.Add(DrawFan(new Vector2(100, 10)));
            fans.Add(DrawFan(new Vector2(450, 110)));
            


            //FIRE
            Vector2 firePosition = new Vector2(0, 420);
            Vector2 fireSize = new Vector2(77, 60);
            Texture2D fireTexture = contentManager.Load<Texture2D>("images\\fire");
            fire = new AnimatedGameObject(world, fireTexture, firePosition, fireSize, 1);
            fire.Position = firePosition;
            fire.Size = fireSize;
            fire.Body = BodyFactory.CreateRectangle(world, ConvertUnits.ToSimUnits(fireSize.X), ConvertUnits.ToSimUnits(fireSize.Y), 10f);
            fire.Body.IsStatic = true;
            fire.Body.Position = ConvertUnits.ToSimUnits(firePosition);
            fire.Body.Restitution = 0.2f;
            fire.Body.Friction = 0.2f;
            
          
            timer.Start();
            base.OnNavigatedTo(e);
        
        }

        private GameObject DrawFloor(Vector2 position)
        {
            Vector2 floorPosition = position;
            Vector2 floorSize = new Vector2(313, 17);
            Texture2D floorTexture = contentManager.Load<Texture2D>("images\\floor");
            GameObject Floor = new GameObject(floorTexture);
            Floor.Position = floorPosition;
            Floor.Size = floorSize;
            Floor.Body = BodyFactory.CreateRectangle(world, ConvertUnits.ToSimUnits(floorSize.X), ConvertUnits.ToSimUnits(floorSize.Y), 10f);
            Floor.Body.Position = ConvertUnits.ToSimUnits(floorPosition.X, floorPosition.Y);
            Floor.Body.IsStatic = true;
            Floor.Body.Restitution = 0.2f;
            Floor.Body.Friction = 0.2f;
            lastPosition = new Vector2();
            lastPosition = floorPosition;
            return Floor;
        }

        private AnimatedGameObject DrawFan(Vector2 position)
        {
            Vector2 fanPosition = position;
            Vector2 fanSize = new Vector2(200, 200);
            Texture2D fanTexture = contentManager.Load<Texture2D>("images\\fan");
            AnimatedGameObject Fan = new AnimatedGameObject();
            Fan.Texture = fanTexture;
            Fan.Position = fanPosition;
            Fan.Size = fanSize;
            Fan.CurrentFrame = 0;
            return Fan;
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Stop the timer
            timer.Stop();

            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            base.OnNavigatedFrom(e);
        }

        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            // TODO: Add your update logic here
            Vector2 speed = new Vector2(4, 0);
            foreach (AnimatedGameObject fan in fans)
            {
                fan.SpriteAnimate(e, 5,3);
                fan.MoveBack(new Vector2(2,0));
            }
            randomFan = new Random();
            fanTimer += (float)e.ElapsedTime.TotalSeconds;
            if (fanTimer >= fanSpace)
            {
                fanTimer = 0;
                fanSpace = randomFan.Next(10, 100);
                fans.Add(DrawFan(new Vector2(800, fanSpace)));
                fanSpace = randomFan.Next(10, 15);
            }
            
            randomFloor = new Random();
            float k;
            floorTimer = (float)(floors.Last().Position.X + floors.Last().Size.X);
            if (space == 1) k = 700;
            else k = 650;
            if (floorTimer <= k)
            {      
                floorTimer = 0f;
                Vector2 height= new Vector2(0,0);
                if (lastPosition.Y <= 170)
                {
                    height.Y = randomFloor.Next(20, 100);
                    height = lastPosition + height;
                }else
                    if (lastPosition.Y >= 300)
                    {
                        height.Y = randomFloor.Next(20, 100);
                        height = lastPosition - height;
                    }
                    else
                    {
                        height.Y = randomFloor.Next(-100, 100);
                        height = lastPosition+ height;
                    }
                floors.Add(DrawFloor(height));
                space=randomFloor.Next(1, 3);
            }

            
            for (int i = 0; i < floors.Count;i++)
            {
                GameObject floorObject = floors[i];
                if (floorObject.OffScreen())
                {
                    world.RemoveBody(floorObject.Body);
                    floors.Remove(floorObject);
                    floorObject= null;
                }
                else
                {
                    floorObject.Move(speed);
                }
            }

            Toast.SpriteAnimate(e, 3,1);
            fire.SpriteAnimate(e,2,1);
            world.Step(Math.Min((float)e.ElapsedTime.TotalMilliseconds *0.001f, (1f / 30f)));
            
        }
  

        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.Gray); //pozadina na ekran

            // TODO: Add your drawing code here

            spriteBatch.Begin();
            Vector2 KAJSECRTANIGEROV = new Vector2();
            //proba na pod
            foreach (AnimatedGameObject fan in fans)
            {
                spriteBatch.Draw(fan.Texture,fan.Position,fan.Recta,Color.White);
            }
            //Toast.Origin = new Vector2(Toast.Body.Position.X, Toast.Body.Position.Y);
            foreach (GameObject floor in floors)
            {
                KAJSECRTANIGEROV = ConvertUnits.ToDisplayUnits(floor.Body.Position);
                KAJSECRTANIGEROV.Y += floor.Size.Y/2;
                KAJSECRTANIGEROV.X -= floor.Size.X / 10;

                spriteBatch.Draw(floor.Texture, KAJSECRTANIGEROV, Color.White);
            }
            spriteBatch.Draw(Toast.Texture, ConvertUnits.ToDisplayUnits(Toast.Body.Position), Toast.Recta, Color.White);
           // spriteBatch.Draw(Toast.Texture, Toast.Body.Position, Toast.Recta, Color.White, 0f, Toast.Origin, 1f, SpriteEffects.None, 0f);

            //sFire.Origin = new Vector2(0f, 0f);
            for (double i = 0; i < height; i += 75)
            {
                fire.Body.Position = ConvertUnits.ToSimUnits(new Vector2(Convert.ToInt32(i), 420));
                spriteBatch.Draw(fire.Texture, ConvertUnits.ToDisplayUnits(fire.Body.Position), fire.Recta, Color.White);
            }


            spriteBatch.End();
            this.OnUpdate(sender, e);
        }
    }
}